const Comment = require("../model/comment.model");
const Notice = require("../model/notice.model");
const User = require("../model/user.model");
// 使用模糊查询需要先引入Op
const seq = require("sequelize");
const Op = seq.Op;

class CommentService {
    /**
     * 创建
     * @returns {Promise<{code: string, message: string}>}
     * @param comment
     */
    async createComment(comment) {
        const res = await Comment.create(comment);
        return res.dataValues;
    }

    /**
     * 更新
     * @param id
     * @param comment
     * @returns {Promise<boolean>}
     */
    async updateComment(id, comment) {
        const res = await Comment.update(comment, {where: {id}});
        return res[0] > 0;
    }

    /**
     * 删除
     * @param id
     * @returns {Promise<boolean>}
     */

    async removeComment(id) {
        const res = await Comment.destroy({where: {id}});
        return res > 0;
    }

    /**
     * 恢复
     * @param id
     * @returns {Promise<boolean>}
     */

    async restoreComment(id) {
        const res = await Comment.restore({where: {id}});
        return res > 0;
    }

    async findComment({pageNum, pageSize, cat_id, info_id}) {
        const offset = (pageNum - 1) * pageSize;
        const whereOpt1 = {};

        cat_id && Object.assign(whereOpt1, {cat_id});
        info_id && Object.assign(whereOpt1, {info_id});

        const {count, rows} = await Comment.findAndCountAll({
            offset: offset,
            limit: pageSize * 1,
            order: [["createdAt", "DESC"]],
            where: whereOpt1,
            include: [
                {
                    model: User,
                    as: "user_info",
                },
            ],
        });
        return {
            pageNum,
            pageSize,
            total: count,
            list: rows,
        };
    }

    async findCommentInfo(id) {
        const whereOpt = {};
        id && Object.assign(whereOpt, {id});

        const res = await Comment.findOne({
            where: whereOpt,
        });

        return res ? res.dataValues : null;
    }
}

module.exports = new CommentService();
